package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.constant.LkdConstant;
import com.chen.constant.MessageConstant;
import com.chen.exception.BaseException;
import com.chen.exception.PasswordErrorException;
import com.chen.exception.UserNotFoundException;
import com.chen.mapper.RoleMapper;
import com.chen.mapper.UserMapper;
import com.chen.pojo.common.PageResult;
import com.chen.pojo.dto.LoginDto;
import com.chen.pojo.dto.UserDto;
import com.chen.pojo.entry.Role;
import com.chen.pojo.entry.User;
import com.chen.pojo.vo.LoginUserVo;
import com.chen.pojo.vo.TaskWorkVo;
import com.chen.pojo.vo.UserInfoVo;
import com.chen.pojo.vo.UserVo;
import com.chen.service.UserService;
import com.chen.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author chen
 * @version 1.0
 * @date 2025/8/15
 * 人员管理业务实现类
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public LoginUserVo login(LoginDto dto) {

        // 传入参数为null
        if (dto == null) {
            throw new BaseException(MessageConstant.PARAMETER_NULL);
        }

        // 根据登录名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getLoginName, dto.getLoginName());
        User user = userMapper.selectOne(wrapper);

        // 用户不存在
        if (user == null) {
            throw new UserNotFoundException();
        }
        // 密码错误
        if (!user.getPassword().equals(dto.getPassword())) {
            throw new PasswordErrorException();
        }

        return LoginUserVo.builder()
                .userId(user.getId())
                .userName(user.getUserName())
                .roleCode(user.getRoleCode())
                .success(true)
                .msg(LkdConstant.LOGIN_SUCCESS)
                .regionId(user.getRegionId())
                .repair(dto.getLoginType() == 1)
                .token(UUID.randomUUID().toString())
                .build();
    }

    /**
     * 分页查询
     *
     * @param pageIndex 起始页
     * @param pageSize  页大小
     * @param userName  用户名
     * @return 结果
     */
    @Override
    public PageResult<UserVo> searchList(Integer pageIndex, Integer pageSize, String userName) {
        List<UserVo> resultList = new ArrayList<>();
        Page<User> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(userName), User::getUserName, userName);
        page = userMapper.selectPage(page, wrapper);
        List<User> users = page.getRecords();
        if (!CollectionUtils.isEmpty(users)) {
            List<Integer> roleIds = users.stream().map(User::getRoleId).toList();
            List<Role> roles = roleMapper.selectBatchIds(roleIds);
            if (!CollectionUtils.isEmpty(roles)) {
                Map<Integer, Role> roleMap = roles.stream().collect(Collectors.toMap(Role::getRoleId, s -> s));
                users.forEach(s -> {
                    UserVo userVo = new UserVo();
                    BeanUtils.copyProperties(s, userVo);
                    userVo.setRole(roleMap.get(s.getRoleId()));
                    resultList.add(userVo);
                });
            }
        }

        PageResult<UserVo> result = new PageResult<>();
        result.setPageIndex(page.getCurrent());
        result.setPageSize(page.getSize());
        result.setTotalPage(page.getPages());
        result.setTotalCount(page.getTotal());
        result.setCurrentPageRecords(resultList);
        return result;
    }

    /**
     * 新增人员
     *
     * @param userDto 人员信息
     * @return 结果
     */
    @Override
    public Boolean addUser(UserDto userDto) {
        User user = new User();
        Role role = roleMapper.selectById(userDto.getRoleId());
        BeanUtils.copyProperties(userDto, user);
        user.setStatus(userDto.getStatus());
        user.setLoginName(userDto.getUserName());
        user.setRoleCode(role.getRoleCode());
        user.setPassword(LkdConstant.DEFAULT_PASSWORD);
        user.setSecret(LkdConstant.SECRET);
        userMapper.insert(user);
        return true;
    }

    /**
     * 修海人员信息
     *
     * @param userId  人员id
     * @param userDto 人员信息
     * @return 结果
     */
    @Override
    public Boolean updateUser(Integer userId, UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setId(userId);
        userMapper.updateById(user);
        return true;
    }

    /**
     * 删除人员信息
     *
     * @param userId 人员id
     * @return 结果
     */
    @Override
    public Boolean deleteUser(Integer userId) {
        userMapper.deleteById(userId);
        return true;
    }

    @Override
    public List<UserVo> getUserByInnerCode(String innerCode) {
        return userMapper.selectUserByInnerCode(innerCode);
    }

    @Override
    public PageResult<TaskWorkVo> searchUserWork(Integer pageIndex, Integer pageSize,
                                                 String userName, Boolean isRepair) {
        Page<TaskWorkVo> page = new Page<>(pageIndex, pageSize);
        Integer repair = Boolean.TRUE.equals(isRepair) ? 1 : 0;
        page = userMapper.selectUserWorkPage(page, userName, repair);

        List<TaskWorkVo> records = page.getRecords();
        List<TaskWorkVo> taskWorkVos = userMapper.selectUserWork(userName, repair);
        // 先按照用户分组
        Map<Integer, List<TaskWorkVo>> taskMap
                = taskWorkVos.stream().collect(Collectors.groupingBy(TaskWorkVo::getUserId));
        // 收集结果
        records.forEach(s -> {
            List<TaskWorkVo> workVos = taskMap.get(s.getUserId());
            s.setTotal((long) workVos.size());
            s.setWorkCount(workVos.stream().filter(t -> LkdConstant.COMPLETED.equals(t.getTaskStatus())).count());
            s.setProgressTotal(workVos.stream().filter(t -> LkdConstant.PROGRESS.equals(t.getTaskStatus())).count());
            s.setCancelCount(workVos.stream().filter(t -> LkdConstant.CANCEL.equals(t.getTaskStatus())).count());
        });

        page.setRecords(records);
        return PageUtils.mapperResult(page);
    }

    @Override
    public UserInfoVo getUserInfoById(Integer userId) {
        return userMapper.selectUserInfoById(userId);
    }
}
